# 预订系统工具集
from pydantic import BaseModel, Field

from tools.sqllite.base_database_tool import BaseDatabaseTools


class BookingParams(BaseModel):
    hotel_id: int = Field(..., description="酒店ID")
    guest_name: str = Field(..., description="客人姓名")
    checkin_date: str = Field(..., description="入住日期 (YYYY-MM-DD)")
    checkout_date: str = Field(..., description="退房日期 (YYYY-MM-DD)")
    room_count: int = Field(1, description="房间数量")

class CancellationParams(BaseModel):
    booking_id: int = Field(..., description="预订ID")

class BookingSystemTools(BaseDatabaseTools):
    async def create_booking(self, params: BookingParams) -> dict:
        """创建酒店预订"""
        try:
            # 先查询酒店信息和可用房间数
            hotel_result = self._execute_query(
                "SELECT name, available_rooms FROM hotels WHERE id = ?",
                (params.hotel_id,),
                fetch=True
            )
            
            hotel_info = hotel_result[0] if hotel_result and isinstance(hotel_result, list) and len(hotel_result) > 0 else None
            if not hotel_info:
                return {"error": "酒店不存在"}

            available_rooms = hotel_info['available_rooms']
            if available_rooms < params.room_count:
                return {"error": "可用房间不足"}

            # 使用事务确保数据一致性
            operations = [
                # 1. 创建预订
                (
                "INSERT INTO bookings (hotel_id, guest_name, checkin_date, checkout_date, room_count, status) VALUES (?, ?, ?, ?, ?, 'confirmed')",
                (params.hotel_id, params.guest_name, params.checkin_date, params.checkout_date, params.room_count)),
                # 2. 更新可用房间数量
                ("UPDATE hotels SET available_rooms = available_rooms - ? WHERE id = ?",
                 (params.room_count, params.hotel_id))
            ]

            results = self._execute_transaction(operations)
            booking_id = results[0]

            return {
                "booking_id": booking_id,
                "status": "confirmed",
                "message": f"成功为 {params.guest_name} 预订酒店"
            }

        except Exception as e:
            return {"error": f"创建预订失败: {str(e)}"}

    async def cancel_booking(self, params: CancellationParams) -> dict:
        """取消预订"""
        try:
            # 先查询预订信息
            booking_result = self._execute_query(
                "SELECT b.*, h.name as hotel_name FROM bookings b JOIN hotels h ON b.hotel_id = h.id WHERE b.id = ?",
                (params.booking_id,),
                fetch=True
            )

            if not booking_result or not isinstance(booking_result, list) or len(booking_result) == 0:
                return {"error": "预订不存在"}

            booking = booking_result[0]

            if booking['status'] == 'cancelled':
                return {"error": "预订已取消"}

            # 执行取消操作的事务
            operations = [
                # 1. 更新预订状态
                ("UPDATE bookings SET status = 'cancelled' WHERE id = ?", (params.booking_id,)),
                # 2. 恢复可用房间数量
                ("UPDATE hotels SET available_rooms = available_rooms + ? WHERE id = ?",
                 (booking['room_count'], booking['hotel_id']))
            ]

            self._execute_transaction(operations)

            return {
                "booking_id": params.booking_id,
                "status": "cancelled",
                "message": f"已成功取消 {booking['guest_name']} 在 {booking['hotel_name']} 的预订"
            }

        except Exception as e:
            return {"error": f"取消预订失败: {str(e)}"}

    async def get_booking_details(self, booking_id: int) -> dict:
        """获取预订详情"""
        try:
            result = self._execute_query(
                "SELECT b.*, h.name as hotel_name, h.location FROM bookings b JOIN hotels h ON b.hotel_id = h.id WHERE b.id = ?",
                (booking_id,),
                fetch=True
            )
            return result[0] if result and isinstance(result, list) and len(result) > 0 else {}
        except Exception as e:
            return {"error": f"获取预订详情失败: {str(e)}"}